package com.jron.cqiu.kernel.execution;

import com.jron.cqiu.kernel.mail.MailOPattern;
import com.jron.cqiu.kernel.mail.IMailOrder;
import com.jron.cqiu.kernel.util.SystemProperties;
import com.jron.cqiu.kernel.process.IProcess;
import com.jron.cqiu.kernel.exception.OrderExecFailedException;
import com.jron.cqiu.kernel.implement.windows.WinExecution;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerMetaData;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;

/**
 * Created by Intellij IDEA.
 *
 * @Author: Yejw
 * @Date: 2008-6-20
 * @Time: 11:51:16
 */
public class ExecutionProxy implements IExecution {

    private static Log log = LogFactory.getLog(ExecutionProxy.class);

    public void execMailOrder(String orderMethod, String orderFrom, String... args) throws OrderExecFailedException {
        MailOPattern mo = MailOPattern.getEnum(orderMethod);

        if (mo.compareTo(MailOPattern.HAKUNAMATATA) == 0) {
            IMailOrder.INSTANCE.sendHelp((args.length == 1 ? args[0] : orderFrom));
            return;
        }

        if (mo.compareTo(MailOPattern.KILL) == 0) {
            switch (args.length) {
                case 1:
                    IProcess.INSTANCE.kill(args[0]);
                    break;
                case 2:
                    IProcess.INSTANCE.kill(args[0], BooleanUtils.toBoolean(args[1]));
                    break;
            }
            return;
        }

        if (mo.compareTo(MailOPattern.KILL_PID) == 0) {
            IProcess.INSTANCE.kill(Integer.parseInt(args[0]));
            return;
        }

        switch (SystemProperties.SYSTEM) {
            case WINDOWS:
                new WinExecution().execMailOrder(orderMethod, args);
                break;
            case LINUX:
                throw new OrderExecFailedException("There is no IExecution implements for the Linux yet");
        }
    }

    public void shutdownScheduler(boolean waitForJobsToComplete) {
        SchedulerFactory sf = new StdSchedulerFactory();
        Scheduler sched = null;
        try {
            sched = sf.getScheduler();
            SchedulerMetaData metaData = sched.getMetaData();
            sched.shutdown(waitForJobsToComplete);
            log.info("\nExecuted " + metaData.numJobsExecuted() + " jobs. SchedulerName: " +
                    metaData.getSchedulerName() + "\n");
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
}
